package com.hlyj.http.base.tool.lib_hlyj_base.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.BatteryManager;
import android.os.Build;
import android.webkit.WebSettings;

import com.github.gzuliyujiang.oaid.DeviceIdentifier;
import com.hlyj.http.base.tool.lib_hlyj_base.BaseApplication;

import java.util.ArrayList;
import java.util.List;


public class DeviceModeUtil {

    private String BRAND = "";

    private static DeviceModeUtil instance;

    public static DeviceModeUtil getInstance() {
        if (instance == null) {
            synchronized (DeviceModeUtil.class) {
                if (instance == null) {
                    instance = new DeviceModeUtil();
                }
            }
        }
        return instance;
    }


//    private boolean isTime() {
//        return BaseApplication.instance.isShowTime() || DataUtils.getInstance().isAgreedAgreement();
//        // DataUtils.getInstance().isAgreedAgreement();
//    }


    /**
     * 获取设备型号
     *
     * @return 具体型号
     */
    public String getDeviceModel() {
            String model = Build.MODEL;
            String brand = Build.BRAND;
            String phoneModel = model;
            return phoneModel;

    }

    public String getOaid() {
    return DeviceIdentifier.getOAID(BaseApplication.instance);
    }

    /**
     * 获取App版本名称
     *
     * @param context
     * @return
     */
    public String getAppVersionName(Context context) {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = null;
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packInfo.versionName;
        return version;
    }

    /**
     * 获取当前应用包名
     * @param context 上下文对象
     * @return 当前应用包名
     */
    public static String getCurrentPackageName(Context context) {
        return context.getPackageName();
    }


    public String getBuildBrand() {

            BRAND = Build.BRAND;
            return BRAND;//google


    }

    public String getAndroidId(Context context) {

            String androidId = DeviceIdentifier.getAndroidID(context);
            return MD5.digest(androidId);


    }

    // 获取 IMEI 号码 (仅在电话功能设备上有效)
    @SuppressLint("MissingPermission")
    public String getIMEI(Context context) {
           return DeviceIdentifier.getIMEI(context);
    }


    public String get_SDK_VERSION() {

            return String.valueOf(Build.VERSION.SDK_INT);

    }

    public boolean isMiuiLimit() {

            String b = getBuildBrand();
            // miui ,13\14\15 不回传
            if (("Redmi".equals(b) || "Xiaomi".equals(b)) &&
                    Build.VERSION.SDK_INT >= 33) {
                return true;
            } else {
                return false;
            }

    }
    /**
     * 判断手机是否正在充电
     *
     * @param context
     * @return
     */
    public String isCharging(Context context) {
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);

        // 获取充电状态
        int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                status == BatteryManager.BATTERY_STATUS_FULL;
        return isCharging ? "1" : "0";
    }
    /**
     *
     * @param context
     * @return 手机充电类型
     */
    public  String getChargingType(Context context) {
        // 创建意图过滤器，监听电池状态变化
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        // 获取当前电池状态
        Intent batteryStatus = context.registerReceiver(null, intentFilter);

        // 获取充电类型
        int chargePlug = batteryStatus != null
                ? batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
                : -1;

        // 判断充电类型并返回相应字符串
        switch (chargePlug) {
            case BatteryManager.BATTERY_PLUGGED_USB:
                return "2";
            case BatteryManager.BATTERY_PLUGGED_AC:
                return "1";
            case BatteryManager.BATTERY_PLUGGED_WIRELESS:
                return "4";
            case 0: // 表示没有充电
                return "0";
            default:
                return "-1";
        }
    }


    /**
     * 获取当前项目包名
     * @return
     */
    public String appPackgeName() {
        return "";
    }
    /**
     * 获取渠道号
     * @return
     */
    public String getCHANNEL() {
        return "";
    }

    /**
     * 获取用户UA
     * @return
     */
    public static String getUserAgent() {
        String userAgent = "";
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                try {
                    userAgent = WebSettings.getDefaultUserAgent(BaseApplication.instance);
                } catch (Exception e) {
                    userAgent = System.getProperty("http.agent");
                }
            } else {
                userAgent = System.getProperty("http.agent");
            }
            StringBuffer sb = new StringBuffer();
            for (int i = 0, length = userAgent.length(); i < length; i++) {
                char c = userAgent.charAt(i);
                if (c <= '\u001f' || c >= '\u007f') {
                    sb.append(String.format("\\u%04x", (int) c));
                } else {
                    sb.append(c);
                }
            }
            userAgent = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userAgent;
    }
    /**
     * 获取CPU型号
     * @return
     */
    public String getCPUName() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return Build.SUPPORTED_ABIS[0];
        } else {
            return Build.CPU_ABI;
        }
    }

    /**
     * 获取当前电量
     * @param context 上下文对象
     * @return 当前电量百分比
     */
    public  String getBatteryLevel(Context context) {
        BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        return String.valueOf(batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY));
    }

    /** 黑名单命中列表逻辑
     * 检查列表中是否有任意一个应用已安装（优化版，找到第一个就返回）
     * @param context 上下文
     * @param packageNames 包名列表
     * @return 如果任一应用已安装则返回true，否则false
     */
    public static boolean isAnyAppInstalledOptimized(Context context, List<String> packageNames) {
        PackageManager pm = context.getPackageManager();
        for (String packageName : packageNames) {
            try {
                pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
                return true;
            } catch (PackageManager.NameNotFoundException e) {
                // 继续检查下一个
            }
        }
        return false;
    }



    /** 黑名单命中列表逻辑
     * 检查列表中是否有任意一个应用已安装（优化版，找到第一个就返回）
     * @param context 上下文
     * @param packageNames 包名列表
     * @return 如果任一应用已安装则返回true，否则false
     */
    public  List<String> getFirstInstalledApp(Context context, List<String> packageNames) {
        List<String> result = new ArrayList<>();
        PackageManager pm = context.getPackageManager();

        for (String packageName : packageNames) {
            try {
                pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
                result.add(packageName);  // 找到第一个已安装的应用
                return result;  // 立即返回
            } catch (PackageManager.NameNotFoundException e) {
                // 继续检查下一个
            }
        }

        return result;  // 如果没有找到任何已安装的应用，返回空集合
    }

    /** 白名单命中列表逻辑
     * 检查设备是否安装了指定的任何应用
     * @param context 上下文
     * @param packageNames 要检查的应用包名列表
     *
     */
    public  List<String> checkAppsInstalled(Context context, List<String> packageNames) {
        List<String> result = new ArrayList<>();
        PackageManager pm = context.getPackageManager();
        for (String packageName : packageNames) {
            try {
                pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
                result.add(packageName);  // 找到第一个已安装的应用
                return result;
            } catch (PackageManager.NameNotFoundException e) {
                // 应用未安装，继续检查下一个
            }
        }
        // 所有应用都未安装
        return result;
    }
}
